<template>
  <div class="activity">
    <nut-tabs
      @change="tabChangeHandler"
      v-model="value"
      :title-scroll="true"
      title-gutter="10"
      :autoHeight="true"
      v-if="activityTitleList">
      <nut-tab-pane :title="t(g)" :pane-key="i" v-for="(game, g, i) in activityTitleList" :key="g">
      </nut-tab-pane>
    </nut-tabs>
    <swiper
      v-if="activityTitleList"
      ref="categoryPageSwiper"
      direction="horizontal"
      :autoplay="false"
      :autoHeight="true"
      :loop="false"
      :disableOnIntercation="false"
      :touchStartPreventDefault="false"
      slidesPerView="auto"
      :centeredSlides="true"
      class="category_page_swiper"
      @swiper="onSwiperInit"
      @slideChange="handleSwiperChange"
    >
      <swiper-slide v-for="(game, g, i) in activityTitleList" :key="g">
        <div class="img_box">
          <template v-for="(v, index) in game" :key="index">
            <img class="imgs" v-if="hasPic(v.pic_link)" v-lazy="hasPic(v.pic_link)" @click="activityDetail(v)" alt="" />
          </template>
          <!-- 红包活动 -->
          <!-- <img
              class="imgs"
              src="/imgs/activity/image3.webp"
              @click="activityDetail({ id: 10010 })"
              alt=""
            /> -->
        </div>
      </swiper-slide>
    </swiper>
    <redBagModal ref="redBagModalRef" :avatarUrl="avatarUrl" />
  </div>
</template>

<script setup lang="ts">
// @ts-nocheck
import { onMounted, onBeforeUnmount, ref, watch } from "vue";
import { useRouter } from "vue-router";
import { Local } from "@/utils/storage";
import pinia from "@/store/index";
import { useI18n } from "vue-i18n";
import redBagModal from "./redEnvelope/components/redBagModal.vue";
// @ts-ignore
// import PullRefresh from '@/components/PullRefresh.vue'
import { User } from '@/store/user';
import { Page } from "@/store/page";
import { storeToRefs } from "pinia";
import { NetPacket } from "@/netBase/NetPacket";
import PKwebsocket from "@/lolo/Ws";
import { Session } from "@/utils/storage";
import { dingZhiActivity, specificActivityKey } from "@/enums/activityEnum";
import { showToast } from "@nutui/nutui";
import { avatarUrl } from "@/utils/commonVar";
// @ts-ignore
import { Swiper, SwiperSlide } from 'swiper/vue';
import 'swiper/css';
import { enablePullToRefresh, disablePullToRefresh } from "@/utils/publicMethods";
// import { redEnvelopeState, useredEnvelopeHooks } from "./redEnvelope/hooks";
const { t } = useI18n();
const { activityTitleList } = storeToRefs(Page(pinia));
const userInfo = User(pinia);
const { info } = storeToRefs(userInfo);
const seleteType: any = ref("home_page_all");
const router = useRouter();
const value = ref(0);
const redBagModalRef: any = ref(null);

const handleActivetys = async (res: any) => {
  await Page(pinia).setActivityTitleList(res.promo);
  sessionStorage.setItem("msg_notify_activites", JSON.stringify(res.promo));
};

// const { envelopeEntry } = useredEnvelopeHooks();

// 判断配置的活动是否有图片路径
const hasPic = (str: string) => {
  if (str?.startsWith("http")) {
    return t(str);
  } else {
    return str;
  }
};

const swiperInstance = ref(null);
const onSwiperInit = (swiper: any) => {
	swiperInstance.value = swiper; // 保存 Swiper 实例
};

const tabChangeHandler = (item: any) => {
  tabChange(item);
  if (swiperInstance.value) {
		swiperInstance.value?.slideTo(item.paneKey, 400); // 切换到特定页面
	}
}

const tabChange = (item: any) => {
  value.value = item.paneKey;
  Session.set("activityNum", item.paneKey);
  const obj: any = {
    0: "home_page_all",
    1: "activities_category_7",
    2: "activities_category_11",
    3: "activities_category_100",
  };
  seleteType.value = obj[item.paneKey];
  window.scrollTo(0, 0);
};

const activityDetail = (item: any) => {
  // todo 红包要根据特定类型判断
  Local.set("activityItem", item);
  if (item.id == 10010) {
    showToast.success(t("not_open"));
    // if (redEnvelopeState.envelopeInfo?.is_open == 1) {
    //   redBagModalRef && redBagModalRef.value?.openMpdal();
    // } else {
    //   if (redEnvelopeState.envelopeInfo?.is_open == 4) {
    //     redEnvelopeState.isShow = true;
    //     redEnvelopeState.isOpen = true;
    //     setTimeout(() => {
    //       redEnvelopeState.isOpenInfo = true;
    //     }, 2000);
    //   } else {
    //     router.push({
    //       path: "/activity/redEnvelope",
    //     });
    //   }
    // }
    return;
  }

  // 特殊活动key, 跳特定页面
  if (specificActivityKey.includes(item.tag)) {
    showToast.success(t("not_open"));
  } else {
    const dingzhiData = dingZhiActivity[item.id];
    if (dingzhiData) {
      if (dingzhiData.isClose) {
        showToast.success(t("not_open"));
      } else {
        router.push(dingzhiData.route);
      }
    } else {
      router.push({
        path: "activityDetail",
        query: {
          content: item.content_key,
        },
      });
    }
  }
};

const getActivityListData = () => {
  const req = NetPacket.req_activites();
  req.show = 1;
  try {
    const data = JSON.parse(sessionStorage.getItem("msg_notify_activites") || "[]");
    if (data && data.length) {
      handleActivetys({
        promo: data
      })
    }
  } catch {}
  PKwebsocket.instance.send(req, false, {
    callbackName: "msg_notify_activites",
    callback: handleActivetys,
  });
};


const handleSwiperChange = (swiper: any) => {
  tabChange({
    paneKey: swiper.activeIndex
  })
}

watch(() => info.value, (n: any, o: any) => {
  if (!o.full_name && n.full_name) {
    getActivityListData();
  }
})

onMounted(async () => {
  seleteType.value = "home_page_all";
  
  // //获取所有活动
  getActivityListData();
  setTimeout(() => {
    enablePullToRefresh()
  }, 0)
});
onBeforeUnmount(() => {
  disablePullToRefresh()
})
</script>

<style lang="scss" scoped>
.activity {
  padding-top: calc(46px + env(safe-area-inset-top));
  overscroll-behavior: contain;
  :deep(.nut-tabs) {
    .nut-tabs__titles {
      padding: 0;
      position: fixed;
      width: 100%;
      left: 0;
      top: 0;
      padding-top: env(safe-area-inset-top);
      z-index: 2;
      background: url('/imgs/home/public_bg.webp') !important;
      background-size: 80% !important;
      margin-bottom: 5px;

      .nut-tabs__titles-item {
        padding: 0 14px !important;
        width: unset;
      }

      .nut-tabs__titles-item__text {
        color: #C6C4F5;
        font-size: 14px;
      }

      .nut-tabs__titles-item.active {
        &::after {
          bottom: 7px;
          width: 44px;
        }

        .nut-tabs__titles-item__text {
          color: #5b6cff;
        }
      }
    }
  }

  .img_box {
    padding: 10px 10px 70px;
    min-height: calc(var(--vh) * 100 - 100px);
  }

  .imgs {
    width: 100%;
    height: 132px;
    margin-bottom: 3px;
    border-radius: 8px;
  }
}
</style>
